package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.article.mapper.ArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleContentMapper articleContentMapper;
    @Autowired
    private ArticleConfigMapper ArticleConfigMapper;
    @Autowired
    private Configuration configuration;
    @Autowired
    FileStorageService fileStorageService;


    /**
     * 加载文章列表
     *
     * @param dto
     * @param i
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Integer i) {
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag("__all__");
        }
        if(i == 3){
            dto.setMinBehotTime(dto.getMaxBehotTime());
        }
        if(i == 2){
            dto.setMaxBehotTime(dto.getMinBehotTime());
        }
        List<ApArticle> load = articleMapper.load(dto,i);

        System.out.println(load);

        return ResponseResult.okResult(load);
    }

    /**
     * 保存文章三剑客
     *
     * @param dto
     */
    @Override
    public ResponseResult saveAll(ArticleDto dto) {
        if(dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle article = null;
        /**
         * 没有id表示新增
         */
        if(dto.getId() == null){
            article = new ApArticle();
            BeanUtils.copyProperties(dto,article);
            save(article);
            ApArticleConfig articleConfig = new ApArticleConfig(article.getId());
            ArticleConfigMapper.insert(articleConfig);
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(dto.getContent());
            articleContentMapper.insert(articleContent);
        }else{
            article = getById(dto.getId());
            if(article!=null){
                BeanUtils.copyProperties(dto,article);
                updateById(article);
                //先查文章内容，在修改
                ApArticleContent apArticleContent = articleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                        .eq(ApArticleContent::getArticleId, article.getId()));

                apArticleContent.setContent(dto.getContent());

                articleContentMapper.updateById(apArticleContent);
            }
            }
        try {
        Template template = configuration.getTemplate("article.ftl");
        StringWriter out = new StringWriter();
        Map<String, Object> params = new HashMap<>();
        params.put("content", JSONArray.parseArray(dto.getContent()));
        template.process(params,out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());

            //3.把html文件上传到minio中
            String path = fileStorageService.uploadHtmlFile("", article.getId() + ".html", is);

            //4.修改ap_article表，保存static_url字段

            article.setStaticUrl(path);
            articleMapper.updateById(article);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }








        return ResponseResult.okResult(article==null?"":article.getId());

    }
}
